﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Snowdreamist.Windows.Document.Adapter
{
    [Serializable]
    [XmlRoot(ElementName = "metadata", Namespace = Utility.Namespace)]
    public class ContentMetadata
    {
        /// <summary>
        /// identity
        /// </summary>
        [XmlAttribute(AttributeName = "identity", Namespace = Utility.Namespace)]
        public string SourceElementIdentity { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "metadata", Namespace = Utility.Namespace)]
    public class UBBContentMetadata : ContentMetadata
    {
        /// <summary>
        /// Try to create metadata from content
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static UBBContentMetadata TryDeserialize(string content)
        {
            try
            {
                UBBContentMetadata metadata = null;

                using (var stm = new MemoryStream(Convert.FromBase64String(content)))
                using (var reader = new StreamReader(stm, Encoding.UTF8))
                {
                    metadata = _xmlSerializer.Deserialize(reader) as UBBContentMetadata;
                }

                return metadata;
            }
            catch
            {
                // nothing
            }

            return null;
        }
        /// <summary>
        /// Json format string
        /// </summary>
        [XmlText]
        public string JsonString { get; set; }
        /// <summary>
        /// Serialize to string
        /// </summary>
        /// <returns></returns>
        public string Serialize()
        {
            using (MemoryStream stm = new MemoryStream())
            using(var writer = new StreamWriter(stm,Encoding.UTF8))
            {
                _xmlSerializer.Serialize(writer, this);
                return Convert.ToBase64String(stm.ToArray());
            }
        }

        #region private

        /// <summary>
        /// xml serializer
        /// </summary>
        private static readonly XmlSerializer _xmlSerializer = new XmlSerializer(typeof(UBBContentMetadata), Utility.Namespace);

        #endregion
    }
}
